<?php
/**
 * Sigin controller.
 *
 * @author Nguyen Hai Ha
 * @version 1.0
 */

class Account_SigninController extends Zend_Controller_Action {

	protected $_application;
	protected $_baseUrl;
	protected $_contextPath;
	protected $_utilities;
	protected $_auth;
	protected $_errors;

	public function init() {
		$this->_baseUrl = $this->_request->getBaseURL ();
		$this->_contextPath = "account/signin";

		$this->view->assign ( "baseUrl", $this->_baseUrl );
		$this->view->assign ( "contextPath", $this->_contextPath );

		$this->_utilities = new Utilities ( );
		$this->view->assign ( "utilities", $this->_utilities );

		$this->_auth = Zend_Auth::getInstance ();
		$this->_auth->setStorage ( new Zend_Auth_Storage_Session ( Constant::SESSION_NAMESPACE ) );

		$this->_application = new Zend_Session_Namespace ( Constant::SESSION_NAMESPACE );
		$this->_errors = array ();

		$this->view->assign ( "pageTitle", "EzGSM : Đăng nhập" );
	}

	public function indexAction() {
		if ($this->getRequest ()->isPost ()) {
			$f = new Zend_Filter_StripTags ( );
			$request = $this->getRequest ();

			$username = $f->filter ( $request->getPost ( "username" ) );
			$password = $f->filter ( $request->getPost ( "password" ) );
			$remember = ( int ) $f->filter ( $request->getPost ( "remember" ) );

			$salt = 'klmn01234opqrst';
			$password = md5 ( $password.$salt );
				
			if (! strlen ( $username ))
			$this->_errors ['username_null'] = "Bạn vui lòng nhập số điện thoại.";
			if (! strlen ( $password ))
			$this->_errors ['password_null'] = "Bạn vui lòng nhập mật khẩu.";
			if (count ( $this->_errors )) {
				$this->_errors ['username'] = $username;
				$this->view->assign ( "errors", $this->_errors );
				$this->render ( "login-form" );
				return;
			}

			$dbAdapter = Zend_Registry::get ( Constant::DB_ADAPTER );
			$tableName = 'eway_user';
			$identColumn = 'usr_mobile';
			$credeColumn = 'usr_password';
			$dbAdapter->setFetchMode ( Zend_Db::FETCH_ASSOC );

			$authAdapter = new Zend_Auth_Adapter_DbTable ( $dbAdapter );

			$authAdapter->setTableName ( $tableName )->setIdentityColumn ( $identColumn )->setCredentialColumn ( $credeColumn )->setCredentialTreatment ( 'MD5(?) AND usr_activated=1' );

			// Set the input credential values to authenticate against.
			$authAdapter->setIdentity ( $username )->setCredential ( $password );

			// Do the authentication.
			$result = $this->_auth->authenticate ( $authAdapter );

			switch ($result->getCode ()) {
				case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
					/** do stuff for nonexistent identity **/
					$this->_errors ['message'] = "Account khong ton tai!";
					$this->_errors ['username'] = $username;
					$this->view->assign ( "errors", $this->_errors );
					$this->render ( "login-form" );
					break;

				case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
					/** do stuff for invalid credential **/
					$userObject = new UserModel ( );
					if (! $userObject->checkUserByAccountAndPassword ( $username, md5 ( $password ) )) {
						// Neu account khong ton tai trong he thong.
						$this->_errors ['message'] = "Số điện thoại này không tồn tại. Bạn vui lòng kiểm tra lại.";
						$this->_errors ['username'] = $username;
						$this->view->assign ( "errors", $this->_errors );
						$this->render ( "login-form" );
					} else {
						// Neu account ton tai trong he thong va chua duoc activate.
						$this->_errors ['message'] = "Tài khoản của bạn chưa được kích hoạt.";
						$this->_errors ['username'] = $username;
						$this->view->assign ( "errors", $this->_errors );
						$this->render ( "login-form" );
					}
					break;

				case Zend_Auth_Result::SUCCESS :
					/** do stuff for successful authentication **/
					// Success : store database row to auth's storage system.
					// (not the password though!)
					$hiddenProperties = array (
						'usr_password',
						'usr_birthday',
						'usr_email',
						'usr_activated',
						'usr_activated_date',
						'usr_created_date',
						'usr_modified_date',
						'usr_coin_amount',
						'usr_city'
						);

						$storage = $this->_auth->getStorage ();

						// store the identity as an object where the password column has
						// been omitted
						$storage->write ( $authAdapter->getResultRowObject ( null, $hiddenProperties ) );

						$role_name = $this->_auth->getIdentity ()->usr_role;
						$login_name = $this->_auth->getIdentity ()->usr_fullname;

						/** Setting role into session */
						$this->_application->currentRole = $role_name;
						$this->_application->loggedUser = $login_name;

						/*
						 Neu nguoi dung check vao o remember, ghi nho nguoi dung.
						 Thoi gian mac dinh cho ghi nho la 2 tuan.
						 */
						if ($remember)
						Zend_Session::rememberMe ( Constant::TIME_REMEMBER_USER );
						else
						Zend_Session::forgetMe ();

						if ($role_name == Constant::EDITOR) {
							$this->_redirect ( "/" . Constant::ADMINISTRATOR );
						} else {
							$this->_redirect ( "/" . $role_name );
						}
						break;

				default :
					/** do stuff for other failure **/
					$this->render ( "login-form" );
					break;
			} // End switch
			return;
		} // End if.


		$this->render ( 'login-form' );
	}

}//End class.